<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Customposts_cuspo
 * sh
 * @author andrea
 */
class CCustomposts_cuspo extends Controller_cuspo {

  public function addPost($name) {
    //INIZIALIZZAZIONE VARIABILI
    global $debug, $config_cuspo;
    /* @var $found Foundation_cuspo */
    $found = USingleton_cuspo::getInstances("F" . ucfirst($name) . "_cuspo");
    /* @var $view View_cuspo */
    $view = USingleton_cuspo::getInstances("View_cuspo");
    /* @var $entity EConcorsi_cuspo */
    $entity = USingleton_cuspo::getInstances("E" . ucfirst($name) . "_cuspo");
    /* @var $checks UChecks_cuspo */
    $checks = USingleton_cuspo::getInstances("UChecks_cuspo");

//PRELIEVO INFORMAZIONI E CHECK
    $titolo = $view->getRequest("titolo");
    $descrizione = $view->getRequest("descrizione");
    $in_evidenza = $view->getRequest("in_evidenza");
    if ($in_evidenza != "y")
      $in_evidenza = "n";
    $errors[] = $checks->check_titolo($titolo);
    $errors[] = $checks->check_descrizione($descrizione);
    if ($in_evidenza == "y")
      $this->make_in_evidenza_unique($config_cuspo['tables'][$name]); //una sola news può essere in evidenza
    $thumbnail = $found->getFile("thumbnail");
    $error = $checks->simplyCheckIfError($errors);
    if ($error == true) {
      echo json_encode($errors);
      die(0);
    }

//INSERIMENTO NEL DATABASE
    if ($thumbnail != false) {
      /* @var $image FImages_cuspo */
      $image = USingleton_cuspo::getInstances("FImages_cuspo");
      $thumbnail = $found->moveUploadedImage();
      $small_image = $found->appendToFileByPath($thumbnail, "_small");
      $big_image = $found->appendToFileByPath($thumbnail, "_big");
      $image->load($thumbnail);
      $image->crop(500, 360);
      $image->save($big_image);
      $image->load($thumbnail);
      $image->crop(300, 150);
      $image->save($small_image);
    }
    else
      $thumbnail = "default";
    $wp_postid = $this->addWordpressPost($titolo, $descrizione, $thumbnail);
    $fields = array(
        "descrizione" => $descrizione,
        "titolo" => $titolo,
        "thumbnail" => $thumbnail,
        "in_evidenza" => $in_evidenza,
        "wp_post_id" => $wp_postid
    );
    $object = $entity->generateObject($fields);
    $query = $found->insertQuery($object);
    $debug->debugLog($query);
    $found->executeQuery($query);
    return;
  }

  public function updatePost($name) {
//INIZIALIZZAZIONE VARIABILI
    global $debug, $config_cuspo;
    /* @var $found Foundation_cuspo */
    $found = USingleton_cuspo::getInstances("Foundation_cuspo");
    /* @var $view View_cuspo */
    $view = USingleton_cuspo::getInstances("View_cuspo");
    /* @var $checks UChecks_cuspo */
    $checks = USingleton_cuspo::getInstances("UChecks_cuspo");

//PRELIEVO INFORMAZIONI E CHECK
    $titolo = $view->getRequest("titolo");
    $descrizione = $view->getRequest("descrizione");
    $id = $view->getRequest("id");
    $in_evidenza = $view->getRequest("in_evidenza");
    if ($in_evidenza == "y")
      $this->make_in_evidenza_unique($config_cuspo['tables'][$name]); //una sola news può essere in evidenza
    $errors[] = $checks->check_titolo($titolo);
    $errors[] = $checks->check_descrizione($descrizione);
    $thumbnail = $found->getFile("thumbnail");
    $error = $checks->simplyCheckIfError($errors);
    if ($error == true) {
      print_r($errors);
      die("errore grave");
    }
    $query = $found->searchQuery(array("*"), $config_cuspo['tables'][$name], array(array("id", "=", $id)));
    $debug->debugLog($query);
    $old_post = $found->getRowsAssoc($query);
    $old_post = $old_post[0];
//INSERIMENTO NEL DATABASE
    if ($thumbnail != false) {
      /* @var $image FImages_cuspo */
      $image = USingleton_cuspo::getInstances("FImages_cuspo");
      $thumbnail = $found->moveUploadedImage();
      $small_image = $found->appendToFileByPath($thumbnail, "_small");
      $big_image = $found->appendToFileByPath($thumbnail, "_big");
      $image->load($thumbnail);
      $image->crop(500, 360);
      $image->save($big_image);
      $image->load($thumbnail);
      $image->crop(300, 150);
      $image->save($small_image);
      $fields = array(
          array("descrizione", $descrizione),
          array("titolo", $titolo),
          array("thumbnail", $thumbnail),
          array("in_evidenza", $in_evidenza)
      );
    } else {
      $fields = array(
          array("descrizione", $descrizione),
          array("titolo", $titolo),
          array("in_evidenza", $in_evidenza)
      );
      $thumbnail = $old_post['thumbnail'];
    }
    if ($thumbnail != "default")
      $thumbnail = $found->urlifyPath($thumbnail);
    $this->updateWordpressPost($titolo, $descrizione, $thumbnail, $old_post['wp_post_id']);
    $query = $found->updateQuery($config_cuspo['tables'][$name], $fields, array(array("id", "=", $id)));
    $found->executeQuery($query);
    return;
  }

  public function getFormInsertPost($form_name) {
    /* @var $view View_cuspo */
    $view = USingleton_cuspo::getInstances("View_cuspo");
    $settings = array(
        "media_buttons" => false,
        "textarea_name" => "descrizione",
        "textarea_rows" => 7,
        "wpautop" => true
    );
    ob_start();
    wp_editor("", "descrizione", $settings);
    $editor = ob_get_contents();
    ob_end_clean();
    $view->assignVar("editor", $editor);
    $view->assignVar("name", $form_name);
    return $view->fetchTpl("insert_post");
  }

  public function getEditPostForm($edit_name, $post_id = 0) {
    if ($post_id == 0)
      return $this->getEditPostList($edit_name);
    global $config_cuspo;
    /* @var $found Foundation_cuspo */
    $found = USingleton_cuspo::getInstances("Foundation_cuspo");
    /* @var $view View_cuspo */
    $view = USingleton_cuspo::getInstances("View_cuspo");
    $list = $this->getEditPostList($edit_name,$post_id);
    $query = $found->searchQuery(array("*"), $config_cuspo['tables'][$edit_name], array(array("id", "=", $post_id)),false," id DESC");
    $results = $found->getRowsAssoc($query);
    $results = $found->urlifyPathsInArray($results, "thumbnail");
    //Assegnazione delle variabili
    $settings = array(
        "media_buttons" => false,
        "textarea_name" => "descrizione",
        "textarea_rows" => 7,
        "wpautop" => true
    );
    ob_start();
    wp_editor($results[0]['descrizione'], "descrizione", $settings);
    $editor = ob_get_contents();
    ob_end_clean();
    $view->assignVar("posts_list", $list);
    $view->assignVar("editor", $editor);
    $view->assignVar("post_da_modificare", $results[0]);
    $view->assignVar("name", $edit_name);
    $view->assignVar("title", $config_cuspo['editPostsTitles'][$edit_name]);
    $view->assignVar("operation", $config_cuspo['editPostsOperations'][$edit_name]);
    return $view->fetchTpl("edit_form");
  }

  public function getEditPostList($edit_name, $selected = 0) {
    global $config_cuspo, $debug;
    /* @var $view View_cuspo */
    $view = USingleton_cuspo::getInstances("View_cuspo");
    /* @var $found Foundation_cuspo */
    $found = USingleton_cuspo::getInstances("Foundation_cuspo");
    $query = $found->searchQuery(array("*"), $config_cuspo['tables'][$edit_name],false,false," id DESC");
    $results = $found->getRowsAssoc($query);
    if ($selected != 0)
      foreach ($results as $key => $value)
        if ($value['id'] == $selected)
          $results[$key]["selected"] = "1";

    $view->assignVar("risultati", $results);
    $view->assignVar("name", $edit_name);
    $view->assignVar("operation", $config_cuspo['editPostsOperations'][$edit_name]);
    return $view->fetchTpl("edit_post");
  }

  public function showPosts($nr_posts, $type) {
    global $config_cuspo, $debug;
    /* @var $view View_cuspo */
    $view = USingleton_cuspo::getInstances("View_cuspo");
    /* @var $found Foundation_cuspo */
    $found = USingleton_cuspo::getInstances("Foundation_cuspo");
    $tpl = false;
    if (preg_match("/\_home/", $type)) {
      $tpl = $type;
      $type = str_replace("_home", "", $type);
    }
    $from = $config_cuspo['tables'][$type];
    if ($type != "concorso" && $type != "news" && $tpl == false) {
      $query = $found->searchQuery(array("*"), $from) . " ORDER BY id DESC LIMIT 0,$nr_posts";
      $results = $found->getRowsAssoc($query);
      $results = $found->urlifyPathsInArray($results, "thumbnail");
      $results = $this->addThumbnailsToResults($results);
      $results = $this->getPermalinksFromResults($results);
      $view->assignVar("risultati", $results);
    } elseif ($tpl != false) {
      $query = $found->searchQuery(array("*"), $from) . " ORDER BY id DESC LIMIT 0,$nr_posts";
      $query = $found->searchQuery(array("*"), $from) . " ORDER BY id DESC LIMIT 0,$nr_posts";
      $results = $found->getRowsAssoc($query);
      $results = $found->urlifyPathsInArray($results, "thumbnail");
      $results = $this->addThumbnailsToResults($results);
      $results = $this->getPermalinksFromResults($results);
      $view->assignVar("risultati", $results);
      $type = $tpl;
    } else {
      $query = $found->searchQuery(array("*"), $from, array(array("in_evidenza", "<>", "y"))) . " ORDER BY id DESC LIMIT 0,$nr_posts";
      $results = $found->getRowsAssoc($query);
      $results = $found->urlifyPathsInArray($results, "thumbnail");
      $results = $this->addThumbnailsToResults($results);
      $results = $this->getPermalinksFromResults($results);
      $view->assignVar("placeholder_small", $config_cuspo['placeholder_small']);
      $view->assignVar("placeholder_big", $config_cuspo['placeholder_big']);
      $view->assignVar("risultati", $results);
      $query = $found->searchQuery(array("*"), $from, array(array("in_evidenza", "=", "y")), "0,$nr_posts", "id DESC");
      $results = $found->getRowsAssoc($query);
      $results = $found->urlifyPathsInArray($results, "thumbnail");
      $results = $this->addThumbnailsToResults($results);
      $results = $this->getPermalinksFromResults($results);
      $view->assignVar("principale", $results[0]);
    }

    $view->assignVar("placeholder_small", $config_cuspo['placeholder_small']);
    $view->assignVar("placeholder_big", $config_cuspo['placeholder_big']);
    return $view->fetchTpl("show_" . $type);
  }

  public function deletePost($post_id, $post_type) {
    global $config_cuspo, $debug;
    /* @var $found Foundation_cuspo */
    $found = USingleton_cuspo::getInstances("Foundation_cuspo");
    $query = $found->searchQuery(array("wp_post_id"), $config_cuspo['tables'][$post_type], array(array("id", "=", $post_id)));
    $wp_post_to_delete = $found->getRowsAssoc($query);
    wp_delete_post($wp_post_to_delete[0]['wp_post_id'], true);
    $query = $found->deleteQuery($config_cuspo['tables'][$post_type], array(array("id", "=", $post_id)));
    $found->executeQuery($query);
    return;
  }

  /**
   * imposta tutte le tuple della tabella a "in_evidenza=n"
   * @param string $table la tabella in cui impostare in_evidenza a n
   */
  public function make_in_evidenza_unique($table) {
    global $debug;
    /* @var $found Foundation_cuspo */
    $found = USingleton_cuspo::getInstances("Foundation_cuspo");
    $query = $found->updateQuery($table, array(array("in_evidenza", "n")), array(array("1", "=", "1")));
    $found->executeQuery($query);
  }

  public function addThumbnailsToResults($results) {
    global $debug;
    /* @var $found Foundation_cuspo */
    $found = USingleton_cuspo::getInstances("Foundation_cuspo");
    foreach ($results as $key => $value) {
      $results[$key]["small_thumb"] = $found->appendToFileByPath($value['thumbnail'], "_small");
      $results[$key]["big_thumb"] = $found->appendToFileByPath($value['thumbnail'], "_big");
    }
    return $results;
  }

  public function addWordpressPost($titolo, $descrizione, $thumbnail) {
    global $config_cuspo, $debug;
    /* @var $view View_cuspo */
    $view = USingleton_cuspo::getInstances("View_cuspo");
    /* @var $found Foundation_cuspo */
    $found = USingleton_cuspo::getInstances("Foundation_cuspo");
    $view->assignVar("titolo", $titolo);
    $view->assignVar("descrizione", $descrizione);
    if ($thumbnail != "default") {
      $thumbnail = $found->urlifyPath($thumbnail);
      $thumbnail = $found->appendToFileByPath($thumbnail, "_big");
    }
    $debug->debugLog($thumbnail);
    $view->assignVar("thumbnail", $thumbnail);
    $view->assignVar("placeholder_small", $config_cuspo['placeholder_small']);
    $view->assignVar("placeholder_big", $config_cuspo['placeholder_big']);
    $html = $view->fetchTpl("full_post");
    $post = array(
        'post_title' => $titolo,
        'comment_status' => "closed",
        'ping_status' => "closed",
        "post_content" => $html,
        "post_type" => "post",
        "post_status" => "publish"
    );
    return wp_insert_post($post);
  }

  public function updateWordpressPost($titolo, $descrizione, $thumbnail, $id) {
    global $config_cuspo;
    /* @var $view View_cuspo */
    $view = USingleton_cuspo::getInstances("View_cuspo");
    $view->assignVar("titolo", $titolo);
    $view->assignVar("descrizione", $descrizione);
    $view->assignVar("thumbnail", $thumbnail);
    $view->assignVar("placeholder_small", $config_cuspo['placeholder_small']);
    $view->assignVar("placeholder_big", $config_cuspo['placeholder_big']);
    $html = $view->fetchTpl("full_post");
    $post = array(
        'ID' => $id,
        'comment_status' => "closed",
        'ping_status' => "closed",
        "post_content" => $html,
        "post_type" => "post",
        "post_title" => $titolo,
        "post_status" => "publish"
    );
    $postid = wp_insert_post($post);
    return $postid;
  }

  public function getPermalinksFromResults($results) {
    global $debug;
    foreach ($results as $key => $value) {
      $results[$key]["permalink"] = get_permalink($value['wp_post_id']);
    }
    return $results;
  }

}

?>
